package com.goexcursion

import javax.servlet.jsp.tagext.TryCatchFinally;

import com.goexcursion.exception.GoExcursionException;
import com.goexcursion.validator.ParameterValidator;

import grails.converters.JSON

class ExcursionController {

	static allowedMethods = [ create:'POST', update:'UPDATE', delete:'DELETE', positiveVote: "PUT", negativeVote: "PUT"]
	ExcursionService excursionService
	ParameterValidator parameterValidator
	
	def create = {
		parameterValidator.validate( request.JSON, "name")
		parameterValidator.validate( request.JSON, "description")
		parameterValidator.validate( request.JSON, "latitude")
		parameterValidator.validate( request.JSON, "longitude")
		parameterValidator.validate( request.JSON, "creatorId")

		try{
			def excursion = excursionService.create(request.JSON.name as String, request.JSON.description as String,
					request.JSON.latitude as Long, request.JSON.longitude as Long,request.JSON.creatorId as Long  )

			render excursion as JSON
		}
		catch (RuntimeException e){
			render(text:e.getMessage(),contentType:'application/json')
		}
	}

	def delete = {
		try{
			excursionService.delete(params.id)
		}
		catch (GoExcursionException e){
			render(text:e.getMessage(),contentType:'application/json')
		}
	}

	def positiveVote = {
		try{
			def totalVotes = excursionService.positiveVote(params.id as Long)
			render(text:totalVotes as String,contentType:'application/json')		}
		catch (GoExcursionException e){
			render(text:e.getMessage(),contentType:'application/json')
		}
	}

	def negativeVote = {
		try{
			def totalVotes = excursionService.negativeVote(params.id as Long)
			render(text:totalVotes as String,contentType:'application/json')
		}
		catch (GoExcursionException e){
			render(text:e.getMessage(),contentType:'application/json')
		}
	}
}
